package com.mock.ems.controller.cooperation;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.DateUtil;
import com.mock.base.util.NumberUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;

import java.util.*;

/**
 * Created by MOCK on 2017/8/17.
 */
public class MerchantController extends Controller {

    public void index() {

        renderJsp("/page/cooperation/merchant/merchant_list.jsp");
    }


    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        String selectSQL = "select a.*,b.referral_phone_,b.referral_name_,b.business_type_ ";

        StringBuilder exceptSelectSQL = new StringBuilder(" from t_ou_shop_auth a inner join t_ou_shop b " +
                " on a.shop_id_ = b.id_ ");
        List<Object> params = new ArrayList<Object>();

        String realName = getPara("real_name_");
        if (StringUtil.isNotEmpty(realName)) {
            exceptSelectSQL.append(" and a.real_name_ like ?");
            params.add("%" + realName.trim() + "%");
        }

        String businessType = getPara("business_type_");
        if (StringUtil.isNotEmpty(realName)) {
            exceptSelectSQL.append(" and b.business_type_ = ?");
            params.add(businessType);
        }


        String phone = getPara("phone");
        if (StringUtil.isNotEmpty(phone)) {
            Long userId = Db.queryLong("select id from user where phone like ? ", '%' + phone + '%');
            if (null != userId) {
                exceptSelectSQL.append(" and a.party_id_ = ? ");
                params.add(userId);
            }
        }


        String referral_name_ = getPara("referral_name_");
        if (StringUtil.isNotEmpty(referral_name_)) {
            exceptSelectSQL.append(" and b.referral_name_ like ?");
            params.add("%" + referral_name_.trim() + "%");
        }

        String referral_phone_ = getPara("referral_phone_");
        if (StringUtil.isNotEmpty(referral_phone_)) {
            exceptSelectSQL.append(" and b.referral_phone_ like ?");
            params.add("%" + referral_phone_.trim() + "%");
        }

        String nickName = getPara("nickName");
        if (StringUtil.isNotEmpty(nickName)) {
            Record userRecord = Db.findFirst("select id from user where nick_name like ? ", '%' + nickName + '%');
            if (null != userRecord) {
                exceptSelectSQL.append(" and a.party_id_ = ?");
                params.add(userRecord.getLong("id"));
            }
        }

        Date begin_time = DateUtil.parseToDate(getPara("begin_time"), DateUtil.FULL_PATTERN);
        Date end_time = DateUtil.parseToDate(getPara("end_time"), DateUtil.FULL_PATTERN);

        if (null != begin_time && end_time == null) {
            exceptSelectSQL.append(" and a.create_time_ >= ? ");
            params.add(begin_time);
        }

        if (null == begin_time && end_time != null) {
            exceptSelectSQL.append(" and a.create_time_ <= ? ");
            params.add(end_time);
        }

        if (null != begin_time && null != end_time) {
            exceptSelectSQL.append(" and a.create_time_ >= ? and a.create_time_ <= ? ");
            params.add(begin_time);
            params.add(end_time);
        }

        exceptSelectSQL.append(" order by a.id_ desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, selectSQL, exceptSelectSQL.toString());
        } else {
            recordList = Db.paginate(pageNumber, pageSize, selectSQL, exceptSelectSQL.toString(), params.toArray());
        }

        if (CollectionUtil.isNotEmpty(recordList.getList())) {
            recordList.getList().forEach(item -> {
                Long user_id = NumberUtil.toLong(item.get("party_id_"));
                Record user = Db.findById("user", user_id);
                if (null != user) {
                    item.set("phone", user.get("phone"));
                    item.set("nick_name", user.get("nick_name"));
                }
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void audit() {

        String id_ = getPara("id");
        Record record = Db.findById("t_ou_shop_auth", "id_", id_);
        if (null != record) {
            Long user_id = NumberUtil.toLong(record.get("party_id_"));
            Record user = Db.findById("user", user_id);
            if (null != user) {
                user.set("status_str", user.getInt("status") == 1 ? "正常" : "冻结");
                record.set("user", user.getColumns());
            }

            String shopId = record.get("shop_id_");
            Record shopRecord = Db.findById("t_ou_shop", "id_", shopId);
            Record cooperation_partner = null;
            if (null != shopRecord) {
                String typeStr = shopRecord.get("business_type_");
                shopRecord.set("business_type_", "online_store".equals(typeStr) ? "线上店" : "oto".equals(typeStr) ? "线上实体店" : "未知类型");
                record.set("shop", shopRecord.getColumns());
                String phone = shopRecord.get("referral_phone_");
                cooperation_partner = Db.findFirst("select * from cooperation_partner where phone = ?", phone);
            }

            if (null != cooperation_partner) {
                cooperation_partner.set("status_str", cooperation_partner.getInt("status") == 1 ? "代理中" : "未代理");
                record.set("agent", cooperation_partner.getColumns());
            }

            String merchantId = record.get("shop_id_");
            Record merchantRatio = Db
                    .findFirst("select id,ratio,sg_merchant_ratio from distribution_merchant_ratio where merchant_id = ? and status = 1 ", merchantId);
            if (null != merchantRatio) {
                merchantRatio.set("ratio", (int) (merchantRatio.getDouble("ratio").doubleValue() * 100) + "");
                merchantRatio.set("sg_merchant_ratio", (int) (merchantRatio.getDouble("sg_merchant_ratio").doubleValue() * 100) + "");
                record.set("ratio", merchantRatio.getColumns());
            }
            setAttr("record", record.getColumns());

            Record areaAgent =
                    Db.findFirst("select * from user a inner join distribution_merchant_areaagent_relation b on a.id = b.area_user_id " +
                            "where b.merchant_user_id = ?", user_id);
            setAttr("areaAgent", areaAgent);
        }

        List<Record> ratioList = Db.find("select id,ratio,sg_merchant_ratio from distribution_ratio_config where status = 1");
        if (CollectionUtil.isNotEmpty(ratioList)) {
            ratioList.forEach(item -> {
                item.set("ratio", (int) (item.getDouble("ratio").doubleValue() * 100) + "");
            });
            setAttr("ratioList", ratioList);
        }

        renderJsp("/page/cooperation/merchant/merchant_audit.jsp");
    }

    @Before(Tx.class)
    public void auditUpdate() {

        Record admin = getSessionAttr("admin");

        String id_ = getPara("id");
        Integer status = getParaToInt("status");
        String status_str = status == 1 ? "audit_succeed" : "audit_fail";
        Record record = Db.findById("t_ou_shop_auth", "id_", id_);
        record.set("status_", status_str);

        Long ratio_id = getParaToLong("ratio_id");

        //创建商家
        if (status == 1) {

            String shopId = record.get("shop_id_");
            Record shopRecord = Db.findById("t_ou_shop", "id_", shopId);
            String referral_phone_ = shopRecord.get("referral_phone_");
            //通过invite_code查找合作伙伴
            Record cooperation_partner_record = Db.findFirst("select user_id from cooperation_partner where phone = ? ", referral_phone_);
            if (null == cooperation_partner_record) {
                renderJson(new JsonResult().status("-1").show("审核失败，无法找到对应的合作伙伴"));
                return;
            }

            Record merchantRecord = new Record();
            Record ratioRecord = Db.findById("distribution_ratio_config", ratio_id);
            merchantRecord.set("merchant_id", shopId)
                    .set("ratio_id", ratio_id)
                    .set("status", 1)
                    .set("create_time", new Date())
                    .set("ratio", ratioRecord.get("ratio"))
                    .set("sg_merchant_ratio", getPara("sg_merchant_ratio"))
                    .set("sg_merchant_factor", ratioRecord.get("sg_merchant_factor"));
            if (!Db.save("distribution_merchant_ratio", merchantRecord)) {
                throw new RuntimeException("save distribution_merchant_ratio record error!");
            }


            //添加商家和合作伙伴关系
            //商家id,非店铺id
            Long merchant_id = NumberUtil.toLong(record.get("party_id_"));
            Long related_id = cooperation_partner_record.getLong("user_id");
            Record userRelation = Db.findFirst("select id from user_relation where user_id = ? and related_id = ? and role = 2",
                    merchant_id, related_id);
            if (null == userRelation) {
                userRelation = new Record();
                userRelation.set("user_id", merchant_id);
                userRelation.set("related_id", related_id);
                userRelation.set("role", 2);
                userRelation.set("status", 1);
                userRelation.set("create_time", new Date());
                if (!Db.save("user_relation", userRelation)) {
                    throw new RuntimeException("save user_relation fail");
                }
            }

            //更新用户成为商家
            Record user = Db.findById("user", merchant_id);
            if (null != user) {
                String role = user.get("role");
                //如果不存在商家角色，则更新
                if (StringUtil.isNotEmpty(role) && role.indexOf("3") == -1) {
                    role += ",3";
                    user.set("role", role)
                            .set("update_time", new Date());
                    if (!Db.update("user", user)) {
                        throw new RuntimeException("update user fail");
                    }
                }
            }

            Long area_agent_id = getParaToLong("area_agent_id");
            //添加商家与区县代理的映射关系
            if (null != area_agent_id) {
                Record merchant_areaagent_relation_record =
                        Db.findFirst("select id from distribution_merchant_areaagent_relation " +
                                " where merchant_user_id = ? and area_user_id = ?", merchant_id, area_agent_id);
                if (null == merchant_areaagent_relation_record) {
                    merchant_areaagent_relation_record = new Record();
                    merchant_areaagent_relation_record.set("merchant_user_id", merchant_id)
                            .set("area_user_id", area_agent_id)
                            .set("status", 1)
                            .set("create_time", new Date());
                    if (!Db.save("distribution_merchant_areaagent_relation", merchant_areaagent_relation_record)) {
                        throw new RuntimeException("save distribution_merchant_areaagent_relation fail");
                    }
                }
            }
        }

        //更新店铺状态
        Record shopRecord = Db.findById("t_ou_shop", "id_", record.getStr("shop_id_"));
        if (null == shopRecord)
            throw new RuntimeException("can not find t_ou_shop record. shop_id_ : " + record.get("shop_id_"));
        shopRecord.set("status_", status == 1 ? "audit_succeed" : "audit_fail");
        if (!Db.update("t_ou_shop", "id_", shopRecord)) {
            throw new RuntimeException("update t_ou_shop fail");
        }

        if (null != admin) {
            record.set("auditor_", admin.get("real_name"));
        }

        record.set("audit_time_", new Date());

        if (Db.update("t_ou_shop_auth", "id_", record)) {
            renderJson(new JsonResult().status("000").show("操作成功"));
            return;
        }
        renderJson(new JsonResult().status("-1").show("操作失败"));
    }

    public void edit() {

        String id_ = getPara("id");
        Record record = Db.findById("t_ou_shop_auth", "id_", id_);
        if (null != record) {
            Long user_id = NumberUtil.toLong(record.get("party_id_"));
            Record user = Db.findById("user", user_id);
            if (null != user) {
                user.set("status_str", user.getInt("status") == 1 ? "正常" : "冻结");
                record.set("user", user.getColumns());
            }

            String shopId = record.getStr("shop_id_");
            Record shopRecord = Db.findById("t_ou_shop", "id_", shopId);
            Record cooperation_partner = null;
            if (null != shopRecord) {
                String typeStr = shopRecord.getStr("business_type_");
                shopRecord.set("business_type_", "online_store".equals(typeStr) ? "线上店" : "oto".equals(typeStr) ? "线上实体店" : "未知类型");
                record.set("shop", shopRecord.getColumns());
                String phone = shopRecord.get("referral_phone_");
                cooperation_partner = Db.findFirst("select * from cooperation_partner where phone = ?", phone);
            }

            if (null != cooperation_partner) {
                cooperation_partner.set("status_str", cooperation_partner.getInt("status") == 1 ? "代理中" : "未代理");
                record.set("agent", cooperation_partner.getColumns());
            }

            String merchantId = record.get("shop_id_");
            Record merchantRatio = Db
                    .findFirst("select id,ratio,sg_merchant_ratio from distribution_merchant_ratio where merchant_id = ? and status = 1 ", merchantId);
            if (null != merchantRatio) {
                Double ratio = merchantRatio.getDouble("ratio").doubleValue();
                Double sg_merchant_ratio = merchantRatio.getDouble("sg_merchant_ratio").doubleValue();

                merchantRatio.set("ratio", (int) (merchantRatio.getDouble("ratio").doubleValue() * 100) + "");
                merchantRatio.set("sg_merchant_ratio", (int) (merchantRatio.getDouble("sg_merchant_ratio").doubleValue() * 100) + "");
                merchantRatio.set("ratioId", (int) (ratio * 10) + "");
                record.set("ratio", merchantRatio.getColumns());
            }
            setAttr("record", record.getColumns());

            Record areaAgent =
                    Db.findFirst("select a.* from user a inner join distribution_merchant_areaagent_relation b on a.id = b.area_user_id " +
                            "where b.merchant_user_id = ?", user_id);
            setAttr("areaAgent", areaAgent);
        }

        List<Record> ratioList = Db.find("select id,ratio,sg_merchant_ratio from distribution_ratio_config where status = 1");
        if (CollectionUtil.isNotEmpty(ratioList)) {
            ratioList.forEach(item -> {
                item.set("ratio", (int) (item.getDouble("ratio").doubleValue() * 100) + "");
            });
            setAttr("ratioList", ratioList);
        }

        renderJsp("/page/cooperation/merchant/merchant_edit.jsp");
    }

    @Before(Tx.class)
    public void editUpdate() {

        String id_ = getPara("id");
        Record record = Db.findById("t_ou_shop_auth", "id_", id_);

        Long ratio_id = getParaToLong("ratio_id");
        String shopId = record.get("shop_id_");

        Record merchantRecord = Db.findFirst("select * from distribution_merchant_ratio where merchant_id = ?",shopId);
        if(merchantRecord == null){
            renderJson(new JsonResult().status("001").show("未找到distribution_merchant_ratio记录"));
            return;
        }
        Record ratioRecord = Db.findById("distribution_ratio_config", ratio_id);
        merchantRecord.set("ratio_id", ratio_id)
                .set("ratio", ratioRecord.get("ratio"))
                .set("sg_merchant_ratio", getPara("sg_merchant_ratio"))
                .set("sg_merchant_factor", ratioRecord.get("sg_merchant_factor"));
        if (!Db.update("distribution_merchant_ratio", merchantRecord)) {
            throw new RuntimeException("save distribution_merchant_ratio record error!");
        }

        //商家id,非店铺id
        Long merchant_id = NumberUtil.toLong(record.get("party_id_"));

        Long area_agent_id = getParaToLong("area_agent_id");
        //添加商家与区县代理的映射关系
        if (null != area_agent_id) {
            Record merchant_areaagent_relation_record =
                    Db.findFirst("select id from distribution_merchant_areaagent_relation " +
                            " where merchant_user_id = ?", merchant_id);
            //未绑定关系，重新绑定新关系
            if (null == merchant_areaagent_relation_record) {
                merchant_areaagent_relation_record = new Record();
                merchant_areaagent_relation_record.set("merchant_user_id", merchant_id)
                        .set("area_user_id", area_agent_id)
                        .set("status", 1)
                        .set("create_time", new Date());
                if (!Db.save("distribution_merchant_areaagent_relation", merchant_areaagent_relation_record)) {
                    throw new RuntimeException("save distribution_merchant_areaagent_relation fail");
                }
            }else{
                //修改绑定关系
                merchant_areaagent_relation_record.set("area_user_id", area_agent_id);
                if (!Db.update("distribution_merchant_areaagent_relation", merchant_areaagent_relation_record)) {
                    throw new RuntimeException("update distribution_merchant_areaagent_relation fail");
                }
            }
        }

        renderJson(new JsonResult().status("000").show("操作成功"));
    }
}
